<script setup lang="ts">
import { ref, computed } from 'vue';
import { NDrawer, NDrawerContent, NDescriptions, NDescriptionsItem, NTable, NTag, NSpace, NButton } from 'naive-ui';
import { fetchMetadataDetail, fetchUpstream, fetchDownstream, type MetadataVO, type DataLineageVO } from '@/service/api/dataplatform/metadata';

const visible = ref(false);
const loading = ref(false);
const metadataDetail = ref<MetadataVO | null>(null);
const upstreamList = ref<DataLineageVO[]>([]);
const downstreamList = ref<DataLineageVO[]>([]);

// 字段列定义
const fieldColumns = [
  { title: '字段名', key: 'fieldName', width: 150 },
  { title: '字段类型', key: 'fieldType', width: 120 },
  { title: '字段注释', key: 'fieldComment', ellipsis: { tooltip: true } },
  {
    title: '可空',
    key: 'nullable',
    width: 80,
    render: (row: any) => h(NTag, { type: row.nullable ? 'warning' : 'success' }, 
      { default: () => row.nullable ? '是' : '否' })
  },
  {
    title: '主键',
    key: 'primaryKey',
    width: 80,
    render: (row: any) => row.primaryKey ? h(NTag, { type: 'error' }, { default: () => '是' }) : '-'
  },
  { title: '默认值', key: 'defaultValue', width: 120 }
];

// 索引列定义
const indexColumns = [
  { title: '索引名', key: 'indexName', width: 150 },
  { title: '索引类型', key: 'indexType', width: 120 },
  {
    title: '唯一',
    key: 'unique',
    width: 80,
    render: (row: any) => h(NTag, { type: row.unique ? 'success' : 'default' }, 
      { default: () => row.unique ? '是' : '否' })
  },
  {
    title: '列',
    key: 'columns',
    render: (row: any) => row.columns?.join(', ') || '-'
  }
];

// 血缘列定义
const lineageColumns = [
  { title: '表名', key: 'tableName', width: 200 },
  { title: '数据库', key: 'databaseName', width: 150 },
  {
    title: '血缘类型',
    key: 'lineageType',
    width: 100,
    render: (row: DataLineageVO) => h(NTag, { type: 'info' }, { default: () => row.lineageType })
  },
  { title: '任务名称', key: 'taskName', width: 150 },
  { title: '任务类型', key: 'taskType', width: 120 }
];

// 解析字段信息
const fields = computed(() => {
  if (!metadataDetail.value?.fields) return [];
  try {
    return typeof metadataDetail.value.fields === 'string' 
      ? JSON.parse(metadataDetail.value.fields) 
      : metadataDetail.value.fields;
  } catch {
    return [];
  }
});

// 解析索引信息
const indexes = computed(() => {
  if (!metadataDetail.value?.indexes) return [];
  try {
    return typeof metadataDetail.value.indexes === 'string' 
      ? JSON.parse(metadataDetail.value.indexes) 
      : metadataDetail.value.indexes;
  } catch {
    return [];
  }
});

// 上游表格数据
const upstreamTableData = computed(() => {
  return upstreamList.value.map(item => ({
    tableName: item.sourceTableName,
    databaseName: item.sourceDatabaseName,
    lineageType: item.lineageType,
    taskName: item.taskName,
    taskType: item.taskType
  }));
});

// 下游表格数据
const downstreamTableData = computed(() => {
  return downstreamList.value.map(item => ({
    tableName: item.targetTableName,
    databaseName: item.targetDatabaseName,
    lineageType: item.lineageType,
    taskName: item.taskName,
    taskType: item.taskType
  }));
});

// 打开抽屉
async function open(id: number) {
  visible.value = true;
  loading.value = true;
  
  try {
    const [detailRes, upstreamRes, downstreamRes] = await Promise.all([
      fetchMetadataDetail(id),
      fetchUpstream(id),
      fetchDownstream(id)
    ]);
    
    metadataDetail.value = detailRes.data;
    upstreamList.value = upstreamRes.data || [];
    downstreamList.value = downstreamRes.data || [];
  } catch (error) {
    console.error('加载元数据详情失败:', error);
  } finally {
    loading.value = false;
  }
}

// 关闭抽屉
function close() {
  visible.value = false;
  metadataDetail.value = null;
  upstreamList.value = [];
  downstreamList.value = [];
}

defineExpose({ open, close });
</script>

<template>
  <NDrawer v-model:show="visible" :width="1000" placement="right">
    <NDrawerContent title="元数据详情" closable>
      <div v-if="loading" class="flex justify-center items-center h-400px">
        <NSpin size="large" />
      </div>

      <div v-else-if="metadataDetail" class="space-y-16px">
        <!-- 基本信息 -->
        <NCard title="基本信息" size="small">
          <NDescriptions :column="2" label-placement="left">
            <NDescriptionsItem label="表名">{{ metadataDetail.tableName }}</NDescriptionsItem>
            <NDescriptionsItem label="数据库">{{ metadataDetail.databaseName }}</NDescriptionsItem>
            <NDescriptionsItem label="数据源">{{ metadataDetail.datasourceName }}</NDescriptionsItem>
            <NDescriptionsItem label="表类型">
              <NTag :type="metadataDetail.tableType === 'TABLE' ? 'success' : 'info'">
                {{ metadataDetail.tableType === 'TABLE' ? '表' : '视图' }}
              </NTag>
            </NDescriptionsItem>
            <NDescriptionsItem label="表注释" :span="2">
              {{ metadataDetail.tableComment || '-' }}
            </NDescriptionsItem>
            <NDescriptionsItem label="数据大小">{{ metadataDetail.dataSizeFormatted }}</NDescriptionsItem>
            <NDescriptionsItem label="行数">
              {{ metadataDetail.rowCount ? metadataDetail.rowCount.toLocaleString() : '-' }}
            </NDescriptionsItem>
            <NDescriptionsItem label="最后采集时间" :span="2">
              {{ metadataDetail.lastCollectTime }}
            </NDescriptionsItem>
            <NDescriptionsItem label="状态">
              <NTag :type="metadataDetail.status === 1 ? 'success' : 'error'">
                {{ metadataDetail.status === 1 ? '启用' : '禁用' }}
              </NTag>
            </NDescriptionsItem>
          </NDescriptions>
        </NCard>

        <!-- 字段信息 -->
        <NCard title="字段信息" size="small">
          <NTable :columns="fieldColumns" :data="fields" :max-height="300" />
        </NCard>

        <!-- 索引信息 -->
        <NCard v-if="indexes.length > 0" title="索引信息" size="small">
          <NTable :columns="indexColumns" :data="indexes" :max-height="200" />
        </NCard>

        <!-- 上游依赖 -->
        <NCard title="上游依赖" size="small">
          <template #header-extra>
            <NTag type="info">{{ upstreamList.length }} 个</NTag>
          </template>
          <NTable 
            v-if="upstreamTableData.length > 0"
            :columns="lineageColumns" 
            :data="upstreamTableData" 
            :max-height="200" 
          />
          <NEmpty v-else description="暂无上游依赖" />
        </NCard>

        <!-- 下游影响 -->
        <NCard title="下游影响" size="small">
          <template #header-extra>
            <NTag type="warning">{{ downstreamList.length }} 个</NTag>
          </template>
          <NTable 
            v-if="downstreamTableData.length > 0"
            :columns="lineageColumns" 
            :data="downstreamTableData" 
            :max-height="200" 
          />
          <NEmpty v-else description="暂无下游影响" />
        </NCard>
      </div>
    </NDrawerContent>
  </NDrawer>
</template>
